<?php

/**
 * @copyright since 9:11 27/4/2020
 * @author <mc@dancis.info>
 */

namespace app;

class App
{
    private static $instance;

    /**
     * @var Db
     */
    private static $db;

    public function __construct()
    {
        if (!static::$instance) {
            $db = new Db;
            if ($db->errno) {
                throw new \RuntimeException('Connection error: #' . $db->connect_errno . ': ' . mysqli_connect_error()); // With historical reason using `mysqli_connect_error`
            }
            static::$db = $db;
        }
        static::$instance[] = $this;
    }

    public static function getInstance()
    {
        return static::$instance ? end(static::$instance): new static;
    }

    public function getDb()
    {
        return static::$db;
    }

    public function verifyUserPassWdUnencrypted($user_id, $password_input)
    {
        return $password_input === $this->getDb()->readPassWd($user_id);
    }

    public function verifyUserPassWdEncrypted($user_id, $password_input)
    {
        return password_verify($password_input, $this->getDb()->readPassWd($user_id));
    }

    public static function run()
    {
        //print_r(static::getInstance()->getDb()->host_info); // Verify connection


        //print_r(static::getInstance()->getDb()->create()); // Creation
        //print_r(static::getInstance()->getDb()->update()); // Updating

        // Reading
        print_r(static::getInstance()->getDb()->read());
        //print_r(static::getInstance()->getDb()->read(668));
        //print_r(static::getInstance()->getDb()->read(1, true));
        //print_r(static::getInstance()->getDb()->readPassWd(1));

        //print_r(static::getInstance()->getDb()->delete(673));


        //var_dump(static::getInstance()->verifyUserPassWdUnencrypted(1, ''));
        //var_dump(static::getInstance()->verifyUserPassWdEncrypted(1, ''));
    }
}
